package edu.sctu.yueding.activitys;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import edu.sctu.yueding.R;
import edu.sctu.yueding.adapter.VoteAdapter;
import edu.sctu.yueding.bean.HomeListViewBean;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.JsonBaseListBean;
import edu.sctu.yueding.bean.MetaBean;
import edu.sctu.yueding.bean.VoteBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.ScreenUntils;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;

/**
 * Created by zhengsenwen on 2016/8/18.
 */
public class VoteActivity extends BaseActivity {

    private ListView listView;
    private List<VoteBean.Items> voteItemBeanList;
    private ImageView back;
    private Button vote;
    private TextView title;
    private WebView webView;
    private final int voteId = SharePreference.getInstance(VoteActivity.this).getInt(CacheConfig.CACHE_VOTE_ID);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vote);
        initViews();
    }


    //清除缓存
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            SharePreference.getInstance(VoteActivity.this).removeOneCache("voteFlag");
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initViews() {

        initWebView();

        back = (ImageView) findViewById(R.id.activity_vote_return);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharePreference.getInstance(VoteActivity.this).removeOneCache(CacheConfig.CACHE_VOTE_ITEM_ID);
                finish();
            }
        });

        String voteTitle = getIntent().getExtras().getString("voteTitle");
        title = (TextView) findViewById(R.id.activity_vote_title);
        title.setText(voteTitle);

        listView = (ListView) findViewById(R.id.vote_listView);
        listView.setVisibility(View.VISIBLE);

        initVoteChooice();

        vote = (Button) findViewById(R.id.activity_vote_vote_button);
        vote.setText("投票");
        vote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean flag = SharePreference.getInstance(VoteActivity.this).getBoolean(CacheConfig.CACHE_VOTE_FLAG);
                if (flag == false) {
                    Toast.makeText(VoteActivity.this, "请您先选择，再进行投票！", Toast.LENGTH_SHORT).show();
                } else {
                    uploadVoteResult();
                }
            }
        });
    }

    /**
     * 加载投票选项
     */
    private void initVoteChooice() {

        Response.Listener<String> listener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {

                JsonBaseListBean<VoteBean> voteBean = JSON.parseObject(
                        json, new TypeReference<JsonBaseListBean<VoteBean>>() {
                        }.getType());
                MetaBean meta = voteBean.getMeta();

                if(meta.getCode() == 200) {

                    List<VoteBean> voteList = voteBean.getData();

                    int votePosition = getIntent().getExtras().getInt("votePosition");
                    voteItemBeanList = voteList.get(votePosition).getItems();

                    listView.setAdapter(new VoteAdapter(VoteActivity.this, voteItemBeanList));
                    setListViewHeightBasedOnChildren(listView);
                }else {
                    Log.d("vote activity json", "Not 200 Not SUCCESS!");
                }

            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vote json", "error  vote json   ...");
            }
        };

        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.URL_HOME_VOTE,
                listener, errorListener, (long) 5000);
    }

    /**
     * 上传投票结果
     */
    private void uploadVoteResult() {

        Response.Listener<String> votedListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                JsonBaseBeen jsonBaseBeen = JSON.parseObject(json, new TypeReference<JsonBaseBeen>() {
                }.getType());
                if (jsonBaseBeen.getMeta().getCode() == 200){
                    Toast.makeText(VoteActivity.this, "您已投票成功！", Toast.LENGTH_SHORT)
                            .show();
                }
                if (jsonBaseBeen.getMeta().getCode() == 40600001){
                    Toast.makeText(VoteActivity.this, "请勿重复投票！", Toast.LENGTH_SHORT)
                            .show();
                }
                Log.e("vote  json ", json);
            }
        };
        Response.ErrorListener votedErrorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vote json", "error  vote json   ...");
            }
        };

        long itemId = (long) SharePreference.getInstance(VoteActivity.this).getInt(CacheConfig.CACHE_VOTE_ITEM_ID);

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("itemId", String.valueOf(itemId));

        GetVolleyHttp.getInstance(VoteActivity.this).getStringPOSTJsonData
                (URLConfig.URL_HOME_VOTE + "/" + voteId + "/records/", map, votedListener, votedErrorListener);
    }

    /**
     * 修改webView
     */
    private void initWebView() {

        webView = (WebView) findViewById(R.id.activity_vote_content);
        String voteContent = getIntent().getExtras().getString("voteContent");

        webView.loadUrl(voteContent);

//        webView.setWebChromeClient(new WebChromeClient() {
//
//        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {

        Adapter listViewAdapter = listView.getAdapter();
        if (listViewAdapter == null) {
            return;
        }

        int totalHeight = 0;
        int viewCount = listViewAdapter.getCount();
        for (int i = 0; i < viewCount; i++) {
            View listItem = listViewAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listViewAdapter.getCount() - 1)) + 10;//加10是为了适配自定义背景
        listView.setLayoutParams(params);
    }

}
